//****************************************************************
//* Copyright (c) 2008 Ford Motor Company. All Rights Reserved.
//*
//* $$Workfile:   ItemCategoryLogic.java  $$
//* $$Revision:   1.1  $$
//* $$Author:   JLOPE262  $$
//* $$Date:   Nov 21 2008 14:22:32  $$
//*
//*****************************************************************
package ar.com.ford.it.fullEconomics.logic;

import java.sql.Timestamp;
import java.util.Collection;
import org.apache.commons.lang.StringUtils;
import ar.com.ford.it.fullEconomics.FullEconomicsPrs;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.persistence.dao.ItemCategoryDao;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesc05Itemcatgry;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.Level;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;

public class ItemCategoryLogic {

    private static final String CLASS_NAME = ItemCategoryLogic.class.getName();
    private static final ILogger log = LogFactory.getInstance().getLogger(
            CLASS_NAME);

    public Teesc05Itemcatgry getItemCategory(Integer itemCategoryNumber,
                                             Teesg01Plant plant)
            throws FullEconomicsException {

        String METHOD_NAME = "getItemCategory";
        log.entering(CLASS_NAME, METHOD_NAME);

        ItemCategoryDao dao = new ItemCategoryDao();

        log.exiting(CLASS_NAME, METHOD_NAME);
        try {
            return dao.getItemCategoryByPK(itemCategoryNumber, plant);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Get Item Category Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.ItemCategory.GET);
        }
    }

    /**
     * Busca los Item Categories segun codigo o nombre.
     * 
     * @param code
     * @param name
     * @return
     * @throws FullEconomicsException
     */
    public Collection<Teesc05Itemcatgry> findItemCategories(String code,
                                                            String name,
                                                            Teesg01Plant plant)
            throws FullEconomicsException {

        String METHOD_NAME = "findItemCategories";
        log.entering(CLASS_NAME, METHOD_NAME);

        Collection<Teesc05Itemcatgry> res = null;
        ItemCategoryDao dao = new ItemCategoryDao();
        Teesc05Itemcatgry itemCategory = new Teesc05Itemcatgry();

        if (StringUtils.isBlank(code)) {
            itemCategory.setEesc05ItemcatgryNumberK(null);
        } else {
            itemCategory.setEesc05ItemcatgryNumberK(Integer.valueOf(code));
        }
        itemCategory.setEesc05ItemcatgryNameN(name);
        itemCategory.setEesc05PlantCodeC(plant);
        try {
            res = dao.findItemCategories(itemCategory);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find Item Category Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.ItemCategory.FIND);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return res;
    }

    /**
     * Busca todos los Item Cateogories pertenecientes a "plant"
     * 
     * @param plant
     * @return
     * @throws FullEconomicsException
     */
    public Collection<Teesc05Itemcatgry> findAllItemCategories(
                                                               Teesg01Plant plant)
            throws FullEconomicsException {

        String METHOD_NAME = "findAllItemCategories";
        log.entering(CLASS_NAME, METHOD_NAME);

        Collection<Teesc05Itemcatgry> res = null;
        ItemCategoryDao dao = new ItemCategoryDao();
        String[] fields = { "eesc05PlantCodeC" };
        Object[] values = { plant };

        try {
            res = dao.findAll(new Teesc05Itemcatgry(), fields, values);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find all Item Categories Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.ItemCategory.FIND_ALL);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return res;
    }

    /**
     * Da de alta el Item Category pasado por parametro
     * 
     * @param itemCategory
     * Item Category a dar de alta
     * @param user
     * Usuario que da de alta el Item Category
     * @throws FullEconomicsException
     */
    public void createItemCategory(Teesc05Itemcatgry itemCategory,
                                   FullEconomicsWslxUser user)
            throws FullEconomicsException {

        String METHOD_NAME = "createItemCategory";
        log.entering(CLASS_NAME, METHOD_NAME);

        ItemCategoryDao dao = new ItemCategoryDao();
        String[] fields = new String[1];
        Object[] values = new Object[1];
        String maxFieldName = null;
        Integer lastCode = null;

        try {
            // Integer lastCode = (Integer)
            // dao.getLastItemCategoryCodeByPlant(user.getTeesg01Plant()).get("maxItemCategoryCode");            
            fields[0] = "eesc05PlantCodeC";
            values[0] = user.getTeesg01Plant();
            maxFieldName = "eesc05ItemcatgryNumberK";
            lastCode = dao.getMax(new Teesc05Itemcatgry(), fields, values,
                    maxFieldName);
            itemCategory.setEesc05ItemcatgryNumberK(lastCode + 1);
            itemCategory.setEesc05CreateUserC(user.getId());
            itemCategory.setEesc05LastUpdtUserC(user.getId());
            itemCategory.setEesc05CreateS(new Timestamp(System
                    .currentTimeMillis()));
            itemCategory.setEesc05LastUpdtS(new Timestamp(System
                    .currentTimeMillis()));
            PersistenceUtil.newTransaction();
            itemCategory.setEesc05PlantCodeC(user.getTeesg01Plant());
            dao.createItemCategory(itemCategory);
            PersistenceUtil.commitTransaction();
        } catch (PersistenceException pe) {
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Create Item Category Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.ItemCategory.CREATE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Actualiza el Item Category pasado por parametro
     * 
     * @param itemCategory
     * Item Category a actualizar
     * @param user
     * Usuario que actualiza el Item Category
     * @throws FullEconomicsException
     */
    public void updateItemCategory(Teesc05Itemcatgry itemCategory,
                                   FullEconomicsWslxUser user)
            throws FullEconomicsException {

        String METHOD_NAME = "updateItemCategory";
        log.entering(CLASS_NAME, METHOD_NAME);

        ItemCategoryDao dao = new ItemCategoryDao();
        Teesc05Itemcatgry workingCopy = null;

        try {
            PersistenceUtil.newTransaction();

            // XXX Ver si esta bien llamar este clearCache aca
            PersistenceUtil.getPersistenceManager().clearCache();

            workingCopy = dao.getItemCategoryForUpdate(itemCategory
                    .getEesc05PlantCodeC(), itemCategory
                    .getEesc05ItemcatgryNumberK());
            workingCopy.setEesc05LastUpdtUserC(user.getId());
            workingCopy.setEesc05LastUpdtS(new Timestamp(System
                    .currentTimeMillis()));
            workingCopy.setEesc05ItemcatgryNameN(itemCategory
                    .getEesc05ItemcatgryNameN());

            PersistenceUtil.commitTransaction();
        } catch (PersistenceException pe) {
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Update Item Category Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.ItemCategory.UPDATE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Elimina el Item Category pasado por parametro
     * 
     * @param itemCategory
     * Item Category a eliminar
     * @throws FullEconomicsException
     */
    public void deleteItemCategory(Teesc05Itemcatgry itemCategory)
            throws FullEconomicsException {

        String METHOD_NAME = "deleteItemCategory";
        log.entering(CLASS_NAME, METHOD_NAME);

        try {
            PersistenceUtil.newTransaction();

            ItemCategoryDao dao = new ItemCategoryDao();
            dao.deleteItemCategory(itemCategory);

            PersistenceUtil.commitTransaction();
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Delete Item Category Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.ItemCategory.DELETE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Se fija si ya existe un Item Category cuyo nombre sea "name"
     * 
     * @param name
     * Nombre del Item Category que quiero ver si existe
     * @return True si ya existe un Item Category cuyo nombre es "name". False
     * en caso contrario
     * @throws FullEconomicsException
     */
    public boolean itemCategoryNameAlreadyExists(String name, Teesg01Plant plant)
            throws FullEconomicsException {

        String METHOD_NAME = "itemCategoryNameAlreadyExists";
        log.entering(CLASS_NAME, METHOD_NAME);

        Collection<Teesc05Itemcatgry> itemCategories = null;
        String[] fields = new String[1];
        Object[] values = new Object[1];
        ItemCategoryDao dao = new ItemCategoryDao();

        try {
            fields[0] = "eesc05PlantCodeC";
            values[0] = plant;
            itemCategories = dao.findAll(new Teesc05Itemcatgry(), fields,
                    values);
            for (Teesc05Itemcatgry itemCategory : itemCategories) {
                if (itemCategory.getEesc05ItemcatgryNameN().trim()
                        .equalsIgnoreCase(name.trim())) {
                    return true;
                }
            }
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Item Category find all Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.ItemCategory.FIND_ALL);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return false;
    }

    /**
     * Determina si el Item Category pasado por parametro puede ser borrado.
     * Esto lo determina segun tenga o no Items haciendo referencia a el
     * 
     * @param itemCategory
     * @return True si puede ser borrado. False en caso contrario
     */
    public boolean itemCategoryCanBeDeleted(Teesc05Itemcatgry itemCategory) {
        return itemCategory.getTeesc06ItemCollection().size() == 0;
    }

}
